package com.hyh.admin.recommend;

import com.hyh.ad.common.core.domain.model.SysUser;
import com.sun.xml.bind.v2.TODO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class RecommendationUserSimilarService {
    private static final Logger log = LoggerFactory.getLogger(RecommendationUserSimilarService.class);

    /**
     * 计算两个用户的相似度（基于用户特征）
     */
    public double calculateUserSimilarityByProfile(UserProfile user1, UserProfile user2) {
        // 提取用户特征（职业、兴趣等）
        List<String> features1 = extractUserFeatures(user1);
        List<String> features2 = extractUserFeatures(user2);

        // 计算 Jaccard 相似度（或者余弦相似度）
        return calculateJaccardSimilarity(features1, features2);
    }

    /**
     * 从用户画像中提取特征
     */
    private List<String> extractUserFeatures(UserProfile user) {
        List<String> features = new ArrayList<>();
        SysUser sysUser = user.getUser();

        features.add(sysUser.getGrade()); // 年级
        features.add(sysUser.getJobTitle()); // 职业
        features.add(sysUser.getIndustry()); // 所处行业

        // 判空，避免 NPE
        String wantResources = sysUser.getWantResources();
        if (wantResources != null && !wantResources.isEmpty()) {
            String[] split = wantResources.split(",");
            features.addAll(Arrays.asList(split)); // 直接添加到列表
        }
        return features;
    }

    /**
     * 计算 Jaccard 相似度
     * 用户计算用户之间的相似度
     */
    private double calculateJaccardSimilarity(List<String> features1, List<String> features2) {
        Set<String> set1 = new HashSet<>(features1);
        Set<String> set2 = new HashSet<>(features2);

        Set<String> intersection = new HashSet<>(set1);
        intersection.retainAll(set2); // 交集

        Set<String> union = new HashSet<>(set1);
        union.addAll(set2); // 并集

        return union.isEmpty() ? 0.0 : (double) intersection.size() / union.size();
    }


    /*
     *  为新用户推荐课程
     */
    public List<String> recommendCoursesForNewUser(UserProfile newUser, List<UserProfile> existingUsers) {
        // 计算新用户与每个已有用户的相似度
        Map<UserProfile, Double> similarityScores = new HashMap<>();
        for (UserProfile existingUser : existingUsers) {
            double similarity = calculateUserSimilarityByProfile(newUser, existingUser);
            log.info("similarity{}",similarity);
            similarityScores.put(existingUser, similarity);
        }

        // 排序，获取最相似的前 K 个用户
        int K = 5; // 取前 5 个最相似的用户
        List<UserProfile> topUsers = similarityScores.entrySet().stream()
                .sorted((a, b) -> Double.compare(b.getValue(), a.getValue())) // 按相似度降序排序
                .limit(K)
                .map(Map.Entry::getKey)
                .collect(Collectors.toList());

        // 获取当前的推荐课程
        Set<String> recommendedCourses = new HashSet<>(newUser.getRecommendedCourses()); // 先取已有的推荐课程

        // 追加相似用户的推荐课程
        for (UserProfile similarUser : topUsers) {
            recommendedCourses.addAll(similarUser.getLikedCourses()); // 推荐相似用户收藏的课程
            recommendedCourses.addAll(similarUser.getRecommendedCourses()); // 推荐相似用户推荐的课程
        }

        return new ArrayList<>(recommendedCourses);
    }
}
